package handler.wx

import com.alibaba.fastjson.JSON

// access token缓存时间
long lastAccessTimeAccessToken = 0
// wexin shi 7200
long expiredMillis = 1000 * 7000
Map cached = [:]

// 企业公众号的oauth
handler.get('/wx/auth-redirect'){req, resp ->
	String code = req.params.code

	String corpid = 'wx1c09b330435520f3'
	String corpsecret = 'v8fkNv0L6DErNNn4JD0U54aSEL9hGWDPI-UeTx1l5eXBsvV_Ye22zpkQCrq7wKgx'
	String agentid = '1'

	String accessToken
	boolean isExpired = (System.currentTimeMillis() - lastAccessTimeAccessToken) > expiredMillis
	if(isExpired){
		String urlGetAccessToken = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpid}&corpsecret=${corpsecret}"
		def objResult = JSON.parseObject(new URL(urlGetAccessToken).text)
		accessToken = objResult.access_token

		cached.accessToken = accessToken
		lastAccessTimeAccessToken = System.currentTimeMillis()

		log.info('get oauth access token from weixin')
	}else{
		accessToken = cached.accessToken

		log.info('get oauth access token from cache')
	}
	
	String urlGetUser = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=${accessToken}&code=${code}&agentid=${agentid}"

	resp.end new URL(urlGetUser).text
}

